import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'index.dart';
import '../../home/home_index/index.dart';
import '../../../common/utils/index.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return const _MainViewGetX();
  }
}

class _MainViewGetX extends GetView<MainController> {
  const _MainViewGetX({Key? key}) : super(key: key);

  // 上次按返回键的时间
  static DateTime? _lastBackPressed;
  
  // 退出提示的持续时间（2秒内再次按返回键才退出）
  static const Duration _exitTimeLimit = Duration(seconds: 2);

  // 构建主要内容区域 - 直接显示首页
  Widget _buildMainContent() {
    return GetBuilder<HomeIndexController>(
      id: "home_index",
      builder: (controller) => const HomeIndexPage(),
    );
  }

  /// 处理返回键按下事件
  Future<bool> _onWillPop() async {
    final now = DateTime.now();
    
    // 如果是第一次按返回键，或者距离上次按返回键超过了时间限制
    if (_lastBackPressed == null || 
        now.difference(_lastBackPressed!) > _exitTimeLimit) {
      
      // 记录这次按键时间
      _lastBackPressed = now;
      
      // 显示退出提示
      _showExitHint();
      
      // 不退出应用
      return false;
    }
    
    // 第二次按返回键且在时间限制内，退出应用
    debugPrint('🚪 用户确认退出应用');
    _exitApp();
    return true;
  }
  
  /// 显示退出提示
  void _showExitHint() {
    debugPrint('🔙 用户按下返回键，显示退出提示');
    
    Get.snackbar(
      '',  // 空标题
      '再按一次退出',
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.black87,
      colorText: Colors.white,
      margin: const EdgeInsets.only(left: 100, right: 100, bottom: 120),
      borderRadius: 12,
      duration: _exitTimeLimit,
      isDismissible: true,
      animationDuration: const Duration(milliseconds: 200),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      titleText: const SizedBox.shrink(),
      messageText: Container(
        height: 24,
        alignment: Alignment.center,
        child: const Text(
          '再按一次退出',
          style: TextStyle(
            color: Colors.white,
            fontSize: 12,
            height: 1.0,
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
  
  /// 退出应用
  void _exitApp() {
    debugPrint('👋 应用即将退出');
    
    Get.closeAllSnackbars();
    SystemNavigator.pop();
  }

  @override
  Widget build(BuildContext context) {
    // 设置主页面状态栏样式
    SystemUIUtils.setTransparentStatusBarDark();
    
    return GetBuilder<MainController>(
      id: "main",
      builder: (_) {
        return WillPopScope(
          onWillPop: _onWillPop,
          child: Scaffold(
            backgroundColor: Colors.white,
            body: _buildMainContent(),
          ),
        );
      },
    );
  }
}
